package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionWithSkus;
import com.atguigu.gulimall.seckill.vo.SeckillSkuVo;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    CouponFeignService couponFeignService ;
    @Autowired
    ProductFeignService productFeignService ;
    @Autowired
    StringRedisTemplate redisTemplate ;
    @Autowired
    RedissonClient redissonClient ;
    @Autowired
    RabbitTemplate rabbitTemplate ;
    private final String SESSIONS_CACHE_PREFIX = "seckill:session:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码
    @Override
    public void uploadSeckillSkuLatest3Days() {
        //扫描需要最近3天参与秒杀的活动
       R session =   couponFeignService.getLates3DaySession();
       if(session.getCode() == 0){
           //上架商品
           List<SeckillSessionWithSkus> sessionData =   session.getData(new TypeReference<List<SeckillSessionWithSkus>>(){});
           //缓存到redis
           System.err.println(sessionData);
           if(sessionData!=null){
               //1缓存活动信息
               saveSessionInfos(sessionData);
               //2缓存活动的关联商品信息
               saveSessionSkuInfos(sessionData);
           }
       }
    }
    //返回当前时间可以参与的秒杀商品
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
//        确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();
        Set<String> keys =  redisTemplate.keys(SESSIONS_CACHE_PREFIX+"*");
        for (String key : keys) {
           String replace = key.replace(SESSIONS_CACHE_PREFIX,"");
           String[] s = replace.split("_");
           Long start = Long.parseLong(s[0]);
           Long end = Long.parseLong(s[1]);
           if(time>=start && time <= end){
               List<String> range =  redisTemplate.opsForList().range(key,-100,100);
               BoundHashOperations<String,String,String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
               List<String> list = hashOps.multiGet(range);
               System.out.println(list);
               if(list!=null){
                   List<SeckillSkuRedisTo> collect =  list.stream().map(item ->{
                       SeckillSkuRedisTo redis = JSON.parseObject((String) item,SeckillSkuRedisTo.class);
                       return  redis ;
                   }).collect(Collectors.toList());
                   return collect ;
               }
               break;
           }
        }
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //找到所有需要参与秒杀的商品的key
        BoundHashOperations<String,String,String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        Set<String> keys =  hashOps.keys();
        if(keys!=null && keys.size()>0){
            String regx = "\\d_"+skuId ;
            for (String key : keys) {
                if(Pattern.matches(regx,key)){
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo skuRedisTo =  JSON.parseObject(json,SeckillSkuRedisTo.class);
                    Long startTime = skuRedisTo.getStartTime();
                    Long endTime = skuRedisTo.getEndTime();
                    Long current = new Date().getTime();
                    if( current >= startTime &&  current <= endTime){
                        return skuRedisTo ;
                    }else {
                        skuRedisTo.setRandomCode(null);
                    }
                };
            }
        }
        return null;
    }

    //TODO 上架秒杀商品的时候，每一个数据都有过期时间。
    //TODO 秒杀后续的流程，简化了收货地址等信息
    @Override
    public String kill(String killId, String key, Integer num) {
        long s1 = System.currentTimeMillis();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get() ;
        //获取当前秒杀商品的详细信息
        BoundHashOperations<String,String,String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = hashOps.get(killId);
        if(StringUtils.isEmpty(s)){
            return null ;
        }else{
            SeckillSkuRedisTo redis = JSON.parseObject(s,SeckillSkuRedisTo.class);
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            Long current = new Date().getTime();
            long ttl = endTime-current ;
            // 判断时间的合法性
            if( current >= startTime &&  current <= endTime){
//                校验随机码和商品id
               String randomCode =  redis.getRandomCode() ;
               String skuId =redis.getPromotionSessionId()+"_"+redis.getSkuId() ;
               if(randomCode.equals(key) && killId.equals(skuId)){
                   //验证购物数量是否合理
                   System.out.println("140-SeckillServiceImpl="+redis.getSeckillLimit());
                   if(num<= redis.getSeckillLimit()){
                       //验证这个人是否已经购买。幂等性；如果秒杀成功就去占位。userId_SessionId
                       //SEINX
                       String redisKey = memberRespVo.getId()+"_"+skuId;
                       //自动过期
                      Boolean aBoolean =  redisTemplate.opsForValue().setIfAbsent(redisKey,num.toString(),ttl,TimeUnit.MILLISECONDS);
                      if(aBoolean){
                          //占位成功说明从来没有买过
                          RSemaphore semaphore =  redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE+randomCode);
                              boolean b = semaphore.tryAcquire(num);
                              //秒杀成功
                              //快速下单，发送MQ消息
                              if(b){
                                  String timeId = IdWorker.getTimeId();
                                  SeckillOrderTo orderTo = new SeckillOrderTo();
                                  orderTo.setOrderSn(timeId);
                                  orderTo.setMemberId(memberRespVo.getId());
                                  orderTo.setNum(num);
                                  orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                  orderTo.setSkuId(redis.getSkuId());
                                  orderTo.setSeckillPrice(redis.getSeckillPrice());
                                  rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);
                                  long s2 = System.currentTimeMillis();
                                  log.info("耗时。。。{}",(s2-s1));
                                  return timeId ;
                              }
                              return null;
                      }else{
                          return null ;
                      }
                   } ;
               }else{
                   return null ;
               }
            }else {
                return  null;
            }
        }
        return null;
    }

    private void saveSessionInfos(List<SeckillSessionWithSkus> sessions){
        sessions.stream().forEach(session -> {
           Long startTime =  session.getStartTime().getTime();
           Long endTime =  session.getEndTime().getTime();
           String key = SESSIONS_CACHE_PREFIX+startTime+"_"+endTime ;
           Boolean haskey = redisTemplate.hasKey(key);
           if(!haskey){
               List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId().toString()
                       +"_"+item.getSkuId().toString()).collect(Collectors.toList());
               //缓存活动信息
               redisTemplate.opsForList().leftPushAll(key,collect);
           }
        });
    }
    private void saveSessionSkuInfos(List<SeckillSessionWithSkus> sessions){
        sessions.stream().forEach(session -> {
            //准备hash操作
            BoundHashOperations<String,Object,Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                String token = UUID.randomUUID().toString().replace("-","");

                if(!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString())){
                    //缓存商品
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //1     sku的基本信息
                    R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if(skuInfo.getCode() == 0){
                        SkuInfoVo info =  skuInfo.getData("skuInfo",new TypeReference<SkuInfoVo>(){});
                        redisTo.setSkuInfo(info);
                    }
                    //2     sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo,redisTo);
                    //3     sku的秒杀信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());
                    //4随机码
                    redisTo.setRandomCode(token);
                    //补充限购次数1
                    redisTo.setSeckillLimit(1);

//                String s= JSON.toJSONString(seckillSkuVo);
                    String jsonString = JSON.toJSONString(redisTo);
                    ops.put(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString(),jsonString);
                    //使用库存作为分布式的信号量 限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE+token);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }
            });
        });
    }
}
